package com.boarsoft.boar.deploy.plan.action;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.LogonI;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.deploy.entity.AppDeployInfo;
import com.boarsoft.boar.deploy.entity.BuildPlanItem;
import com.boarsoft.boar.deploy.plan.PlanAppBiz;
import com.boarsoft.boar.deploy.plan.PlanLibBiz;
import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.lib.LibAppBiz;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.web.login.Logined;

@RestController
@RequestMapping("/plan/lib")
public class PlanLibAction {
	private static final Logger log = LoggerFactory.getLogger(PlanLibAction.class);

	@Autowired
	private PlanLibBiz planLibBiz;
	@Autowired
	private LibAppBiz libAppBiz;
	@Autowired
	private PlanAppBiz planAppBiz;

	@RequestMapping("/save.do")
	@Authorized(code = "deploy.plan.lib.save")
	public ReplyInfo<Object> save(@Logined LogonI<String> logon, BuildPlanItem o, String targetIds) {
		for (String libId : targetIds.split(",")) {
			o.setTargetId(libId);
			o.setOwnerId(logon.getId());
			ReplyInfo<Object> ro = planLibBiz.save(o);
			if (ro.isSuccess()) {
				// 查询依赖此Lib的App
				List<AppInfo> aLt = libAppBiz.list(libId);
				// 遍历这些App，逐一带入当前部署计划（已存在的则跳过）
				for (AppInfo a : aLt) {
					this.save(o.getPlanId(), (AppDeployInfo) a, logon.getId());
				}
				continue;
			}
			log.error("Error on save build plan file item, reason: {}", ro.getData());
			return ro;
		}
		return ReplyInfo.SUCCESS;
	}

	private void save(String planId, AppDeployInfo a, String ownerId) {
		BuildPlanItem x = new BuildPlanItem();
		x.setCode(a.getCode());
		x.setCreateTime(Util.getStdmfDateTime());
		x.setLastTime(x.getCreateTime());
		x.setOwnerId(ownerId);
		x.setName(a.getName());
		x.setPackPath(a.getPackPath2());
		x.setPlanId(planId);
		x.setSourcePath(a.getSourcePath());
		x.setTargetId(a.getId());
		x.setType(BuildPlanItem.TYPE_APP);
		x.setVer(a.getVer());
		planAppBiz.save(x);
	}
}